package com.mallcai.bigdata.ladon.service.report.impl.handler;

import com.mallcai.bigdata.ladon.client.vo.ReportDataVO;
import com.mallcai.bigdata.ladon.datasource.RunInfoResult;
import com.mallcai.bigdata.ladon.dpl.vo.DataType;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryContext;
import com.mallcai.bigdata.ladon.service.report.impl.ReportQueryParamHolder;
import com.mallcai.bigdata.ladon.utils.CollectionUtils;
import com.mallcai.bigdata.ladon.utils.DateUtils;
import com.mallcai.bigdata.ladon.vo.Pair;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author feixy
 * @version 1.0
 * @date 2019-07-20 13:06
 */
@Slf4j
@Service
@Order(6950)
public class FormatSqlPostHandler extends AbstractReportQueryPostHandler {

    @Override
    protected void postInternal(ReportQueryContext context) {
        RunInfoResult<ReportDataVO> result = context.getResult();
        Assert.notNull(result, "查询结果不能为空");
        LinkedHashMap<Integer, Pair<ReportQueryParamHolder, Object>> sqlParams = context.getSqlParams();
        if (CollectionUtils.isNotEmpty(sqlParams)){
            String sql = result.getSql();
            for (Map.Entry<Integer, Pair<ReportQueryParamHolder, Object>> entry : sqlParams.entrySet()) {
                Object obj = entry.getValue().getRight();
                String objStr = String.valueOf(obj);
                if (obj instanceof String){
                    objStr = String.format("'%s'", objStr);
                } else if (obj instanceof Date){
                    try{
                        ReportQueryParamHolder paramHolder = entry.getValue().getLeft();
                        DataType dataType = paramHolder.getDataType();
                        if (dataType == DataType.DATE) {
                            objStr = DateUtils.formatDate((Date)obj, DateUtils.DATE_FORMAT_DATE);
                        }
                        if (dataType == DataType.DATETIME){
                            objStr = DateUtils.formatDate((Date)obj, DateUtils.NORMAL_DATE_FORMAT);
                        }
                    }catch(Throwable e){
                        // 防御性错误
                    }
                    objStr = String.format("'%s'", objStr);
                }
                sql = sql.replaceFirst("\\?", objStr);

            }
            result.setSql(sql);
        }
    }
}
